package com.yds.developtools.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * 用于将 assets 目录下的 APK 文件复制到设备的外部存储
 */
object YDSAssetsToSDCardHelper {

    /**
     * 将 assets 目录下的 APK 文件复制到设备的外部存储
     * @param context 上下文
     * @param assetFileName "xxx.apk"
     * @param outputFileName "xxx.apk"
     * @return callback 复制到外部存储的文件地址
     */
    fun extractApkFromAssets(context: Context, assetFileName: String, outputFileName: String, callback: (String) -> Unit) {
        var outputFilePath = ""
        try {
            val inputStream = context.assets.open(assetFileName)
            val outputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            val outputFile = File(outputDir, outputFileName)
            val outputStream = FileOutputStream(outputFile)
            val buffer = ByteArray(1024)
            var length: Int
            while ((inputStream.read(buffer).also { length = it }) > 0) {
                outputStream.write(buffer, 0, length)
            }
            outputStream.flush()
            outputStream.close()
            inputStream.close()
            outputFilePath = outputFile.absolutePath
        } catch (e: IOException) {
            e.printStackTrace()
            outputFilePath = ""
        } finally {
            callback(outputFilePath)
        }
    }
}
